package cn.zhxu.toys.cipher;

import cn.zhxu.toys.util.DigestUtils;

import java.security.MessageDigest;

/**
 * Md5辅助类
 * Created by admin on 2015/11/5.
 */
public class Md5Utils {

    static final byte[] hexBytes = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 该方法返回的字节数组长度翻倍，推荐使用 {@link DigestUtils#toMd5(byte[])} 方法，该方法不翻倍
     * @return 长度 32 的字节数组
     */
    @Deprecated
    public static byte[] toMd5(byte[] src) {
       	if (src == null) {
    		return null;
    	}
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(src);
        } catch (Exception e) {
            throw new RuntimeException("MD5编码异常：", e);
        }
        byte[] datas = md.digest(); 	//16个字节的长整数
        byte[] bytes = new byte[2 * 16];
        int k = 0;
        for (int i = 0; i < 16; i++) {
            byte b = datas[i];
            bytes[k++] = hexBytes[b >>> 4 & 0xf];//高4位
            bytes[k++] = hexBytes[b & 0xf];//低4位
        }
        return bytes;
    }

}

